﻿
using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Entities;
using Dora.Services.AdminUser.IApplication;
using Dora.Services.AdminUser.Repository.Repositorys;
using Dora.Tools.Utility.Const;
using Microsoft.Extensions.Logging;
using Surging.Core.Common;
using Surging.Core.CPlatform.Ioc;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Dora.Services.AdminUser.Application.Base;
using Dora.Tools.Utility;
using Dora.Services.AdminUser.Dto.ViewDto;
using System.Linq;
using Dora.Tools.Utility.Redis;
using Dora.Tools.Utility.Models;
using Dora.Tools.Enums.AdminUser;
using Dora.Services.AdminUser.Dto.SaveDto;
using Dora.Tools.Enums;

namespace Dora.Services.AdminUser.Application
{

    /// <summary>
    /// 供应商用户表服务
    /// </summary>
    [ModuleName(DoraModuleName.AdminUser)]
    public class SrmUserService : DoraServiceBase, ISrmUserService
    {
        private ISugarUnitOfWork _unitOfWork;
        private readonly SrmUserRepository _repository;
        private readonly SrmUserRoleMapRepository _srmUserRoleMapRepository;
        private readonly PermissionRepository _permissionRepository;
        private readonly RoleRepository _roleRepository;
        //private readonly SrmUserLoginLogRepository _srmUserLoginLogRepository;
        public SrmUserService(ISugarUnitOfWork unitOfWork) 
        {
            _unitOfWork = unitOfWork;
            _repository = new SrmUserRepository(unitOfWork);
            _srmUserRoleMapRepository = new SrmUserRoleMapRepository(unitOfWork);
            _permissionRepository = new PermissionRepository(unitOfWork);
            _roleRepository = new RoleRepository(unitOfWork);
            //_srmUserLoginLogRepository = new SrmUserLoginLogRepository(unitOfWork);
        }


        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ResultDto<SrmUserEntity>> Create(SrmUserEntity entity)
        {
            entity.CreatedTime = DateTime.Now;
            entity.UpdatedTime = DateTime.Now;
            entity.PasswordSalt = Guid.NewGuid().ToString();

            if (!VerifyHelper.IsMobilePhone(entity.Mobile))
            {
                return ResultDto<SrmUserEntity>.Error("请输入正确的手机号");
            }

            if (string.IsNullOrWhiteSpace(entity.RealName))
            {
                return ResultDto<SrmUserEntity>.Error("请输入真实姓名");
            }


            var existMobile = await _repository.ExistVerifiedMobile(entity.Mobile, entity.Id);
            if (existMobile)
            {
                return ResultDto<SrmUserEntity>.Error("手机号已经存在");
            }

            entity.MobileIsVerified = 1;
            entity.NickName = entity.RealName;

            if (string.IsNullOrEmpty(entity.Password))
            {
                entity.Password = DEncryptHelper.GetInitPassword(entity.Mobile, entity.PasswordSalt);
            }
            else
            {
                entity.Password = DEncryptHelper.GetInitPassword(entity.Password, entity.PasswordSalt);
            }

            var modifyClient = _unitOfWork.ModifyClient;
            try
            {
                modifyClient.Ado.BeginTran();
                //var adminRole = _unitOfWork.QueryClient.Queryable<RoleEntity>().First(item => item.RoleNO == ConstValue.SrmAdminRoleNo); 
                //if (adminRole == null)
                //{
                //    return ResultDto<SrmUserEntity>.Error("获取默认权限失败");
                //}
                var result = modifyClient.Insertable(entity).ExecuteReturnEntity();
                if(result == null)
                {
                    modifyClient.Ado.CommitTran();
                    return ResultDto<SrmUserEntity>.Error("添加账号失败");
                }
                result.Password = "";//不给前台返回
                result.PasswordSalt = "";//不给前台返回
                //设置默认权限角色
                //SrmUserRoleMapEntity userRoleEntity = new SrmUserRoleMapEntity()
                //{
                //    UserId = result.Id,
                //    RoleId = adminRole.Id
                //};
                //List<SrmUserRoleMapEntity> userRoleList = new List<SrmUserRoleMapEntity>();            
                //userRoleList.Add(userRoleEntity);
                //modifyClient.Insertable(userRoleList).ExecuteCommand();
                modifyClient.Ado.CommitTran();
                return ResultDto<SrmUserEntity>.Success(result);
            }
            catch(Exception ex)
            {
                modifyClient.Ado.RollbackTran();
                Console.WriteLine(ex);
                return ResultDto<SrmUserEntity>.Error("添加账号失败");
            }
        }


        /// <summary>
        /// 根据Id获取一个实体对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SrmUserEntity> GetById(Guid id)
        {
            return await _repository.FirstOrDefaultAsync(id);
        }


        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<SrmUserListDto>> GetPageList(SrmUserQueryDto input)
        {
            #region 部门Id转换成用户Id
            if (input.DepartmentIdList?.Count > 0)
            {
                //var userIdList = await _edmRepository.GetEmployeeIdListByDeptIdList(input.DepartmentIdList);
                //if (input.UserIdList == null)
                //{
                //    input.UserIdList = new List<Guid>();
                //}

                //if (userIdList?.Count > 0)
                //{
                //    input.UserIdList.AddRange(userIdList);
                //}
                //else
                //{
                //    input.UserIdList.Add(Guid.Empty);
                //}
            }
            #endregion
            var result = await _repository.GetPageList(input);
            if (result?.PageData?.Count() > 0)
            {
                var userIdList = result.PageData.Select(p => p.Id).ToList();
                #region 加载部门与角色
                //var deptAllList = await _edmRepository.GetListByEmployeeIdList(employeeIdList);
                if (input.IsLoadRoleName.HasValue && input.IsLoadRoleName.Value)
                {
                    var roleAllList = await _srmUserRoleMapRepository.GetListByUserIdList(userIdList);
                    foreach (var item in result.PageData)
                    {

                        if (roleAllList?.Count > 0)
                        {
                            item.RoleName = "";
                            var list = roleAllList.Where(it => it.UserId == item.Id);
                            if (list?.Count() > 0)
                            {
                                item.RoleName = string.Join(ConstValue.ChineseSeparatorChar, list.Select(it => it.RoleName).ToArray());
                            }
                        }

                    }
                }
                #endregion
            }
            return result;
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ResultDto> Update(SrmUserEntity entity)
        {
            if (entity == null)
            {
                return ResultDto.Error("用户不存在");
            }

            if (!VerifyHelper.IsMobilePhone(entity.Mobile))
            {
                return ResultDto.Error("请输入正确的手机号");
            }

            if (string.IsNullOrWhiteSpace(entity.RealName))
            {
                return ResultDto.Error("请输入真实姓名");
            }

            var existMobile = await _repository.ExistVerifiedMobile(entity.Mobile, entity.Id);
            if (existMobile)
            {
                return ResultDto.Error("手机号已经存在");
            }

            entity.UpdatedTime = DateTime.Now;
            entity.NickName = entity.RealName;

            var result = await _repository.Update(entity);
            if (result)
            {
                return ResultDto.Success("修改成功");
            }
            else
            {
                return ResultDto.Error("修改失败");
            }
        }

        /// <summary>
        /// 根据IdList获取列表
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<List<SrmUserEntity>> GetList(List<Guid> idList)
        {
            if (idList == null || idList.Count == 0)
            {
                return new List<SrmUserEntity>();
            }
            var list =await _repository.GetAllListAsync(it => idList.Contains(it.Id));
            return list;
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<SrmUserEntity>> GetAll()
        {
            var list =await _repository.GetAllListAsync();
            return list;
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> Delete(Guid id)
        {
            return await _repository.Delete(id);
        }
        public async Task<ResultDto<IdentityUserDto>> Login(string userName, string pwd, string ip, string systemKey)
        {
            var entity = new SrmUserEntity();
            if (VerifyHelper.IsMobilePhone(userName))
            {
                entity = await _repository.GetByVerifiedMobile(userName);
            }
            else if (VerifyHelper.IsEmail(userName))
            {
                entity = await _repository.GetByVerifiedEmail(userName);
            }
            else
            {
                entity = await _repository.GetByUserName(userName);
            }


            if (entity == null)
            {
                return ResultDto<IdentityUserDto>.Error("用户名密码错误");
            }
            if (string.IsNullOrWhiteSpace(entity.Password) || string.IsNullOrWhiteSpace(entity.Password))
            {
                return ResultDto<IdentityUserDto>.Error("用户名或密码不能为空");
            }

            var encryPwd = DEncryptHelper.MD5Salt(pwd, entity.PasswordSalt);
            if (entity.Password != encryPwd)
            {
                return ResultDto<IdentityUserDto>.Error("用户名密码错误");
            }
            return await JudegLogin(entity, ip, UserLoginType.UserNameAndPwd, systemKey);
        }

        public async Task<ResultDto<IdentityUserDto>> LoginByMobile(string mobile, string ip, string systemKey)
        {
            if (!VerifyHelper.IsMobilePhone(mobile))
            {
                return ResultDto<IdentityUserDto>.Error("请输入正确的手机号");
            }

            var entity = await _repository.GetByVerifiedMobile(mobile);


            if (entity == null)
            {
                return ResultDto<IdentityUserDto>.Error("用户不存在");
            }

            return await JudegLogin(entity, ip, UserLoginType.Mobile, systemKey);
        }

        private async Task<ResultDto<IdentityUserDto>> JudegLogin(SrmUserEntity entity, string ip, UserLoginType loginType, string systemKey)
        {
            if (entity == null)
            {
                return ResultDto<IdentityUserDto>.Error("用户名密码错误");
            }
            if (entity.IsDisabled == 1)
            {
                return ResultDto<IdentityUserDto>.Error("用户被禁用");
            }
            else if (entity.IsDeleted == 1)
            {
                return ResultDto<IdentityUserDto>.Error("用户名密码错误");
            }
            else
            {
                var authKeyList = new List<AuthKeyItem>();

                var permissions = new List<PermissionEntity>();
                if (entity.IsSuperAdmin == 1)
                {
                    permissions = await _permissionRepository.GetAllListAsync(it => it.SystemKey == systemKey && it.IsDeleted == 0);
                }
                else
                {
                    permissions = await _permissionRepository.GetSrmAuthedListByUserId(entity.Id);
                }
                if (permissions?.Count > 0)
                {
                    //authKeyList = permissions.Select(p => p.AuthKey).ToList();

                    foreach (var item in permissions)
                    {
                        authKeyList.Add(new AuthKeyItem() { AuthKey = item.AuthKey, Name = item.Name, Icon = item.Icon, Sort = item.Sort });
                    }
                }

                _ = WriteLoginLog(systemKey, entity.SupplierId, entity.Id, entity.UserName, entity.RealName, ip, loginType);
                entity.Password = "";//不给前台返回
                entity.PasswordSalt = "";//不给前台返回

                var userDto = new IdentityUserDto
                {
                    Id = entity.Id,
                    SystemKey = DoraSysIdentifier.SRM.ToDescription(),
                    Avatar = entity.Avatar,
                    IsSuperAdmin = entity.IsSuperAdmin,
                    Mobile = entity.Mobile,
                    MobileIsVerified = entity.MobileIsVerified == 1 ? true : false,
                    RealName = entity.RealName,
                    UserName = entity.UserName,
                    AuthKeyList = authKeyList,
                    Supplier=new SupplierDto() {Id=entity.SupplierId } ,
                    HxUserName = entity.HxUserName
                };

                return ResultDto<IdentityUserDto>.Success("登录成功", userDto);
            }
        }

        public async Task<SrmUserEntity> GetByUserName(string userName)
        {
            return await _repository.GetByUserName(userName);
        }
        public async Task<SrmUserEntity> GetByMobile(string mobile)
        {
            return await _repository.GetByMobile(mobile);
        }

        public async Task<ResultDto> UpdatePassword(Guid userId, string oldPassword, string newPassword)
        {
            var oldEntity = await GetById(userId);
            if (oldEntity == null)
            {
                return ResultDto.Error("用户不存在", false);
            }
            if (string.IsNullOrWhiteSpace(newPassword))
            {
                return ResultDto.Error("密码不能为空", false);
            }

            var saltOldPassword = DEncryptHelper.MD5Salt(oldPassword, oldEntity.PasswordSalt);
            var saltNewPassword = DEncryptHelper.MD5Salt(newPassword, oldEntity.PasswordSalt);
            var mobilePassward = DEncryptHelper.GetInitPassword(oldEntity.Mobile, oldEntity.PasswordSalt);
            //if (saltNewPassword == mobilePassward)
            //{
            //    return ResultDto.Error("请不要使用默认密码作为新密码", false);
            //}
            if (saltNewPassword == saltOldPassword)
            {
                return ResultDto.Error("请使用和原密码不一样的新密码", false);
            }
            if (saltOldPassword != oldEntity.Password)
            {
                return ResultDto.Error("原密码错误", false);
            }

            oldEntity.Password = saltNewPassword;

            var result = await _repository.UpdatePassword(oldEntity);
            if (result)
            {
                return ResultDto.Success("修改成功", result);
            }
            else
            {
                return ResultDto.Error("修改失败", result);
            }
        }

        public async Task<List<SrmUserListDto>> GetListWithRoles(List<Guid> idList)
        {
            try
            {
                var userEntityList = await GetList(idList);
                var userList = new List<SrmUserListDto>();
                if (userEntityList?.Count > 0)
                {
                    var roleListAll = await _srmUserRoleMapRepository.GetListByUserIdList(idList);
                    if (roleListAll?.Count > 0)
                    {
                        foreach (var item in userEntityList)
                        {
                            var ermList = roleListAll.Where(p => p.UserId == item.Id).ToList();
                            SrmUserListDto dtoItem = new SrmUserListDto()
                            {
                                Id = item.Id,
                                UserName = item.UserName,
                                Mobile = item.Mobile,
                                MobileIsVerified = item.MobileIsVerified,
                                Email = item.Email,
                                EmailIsVerified = item.EmailIsVerified,
                                RealName = item.RealName,
                                Sex = item.Sex,
                                Sort = item.Sort,
                                IsDisabled = item.IsDisabled,
                                IsFrozen = item.IsFrozen,
                                IsSuperAdmin = item.IsSuperAdmin,
                                Avatar = item.Avatar,
                                Remark = item.Remark,
                                UserRoleMapList = ermList,
                                SupplierId = item.SupplierId

                            };
                            if (dtoItem.UserRoleMapList == null)
                            {
                                dtoItem.UserRoleMapList = new List<SrmUserRoleMapListDto>();
                            }

                            userList.Add(dtoItem);
                        }
                    }
                }
                return userList;
            }
            catch (Exception ex)
            {
                //WriteOperationLog(EmployeeOperationType.Error, JsonConvert.SerializeObject(list), 0, "系统", ex.Message);
                return new List<SrmUserListDto>();
            }
        }

        public async Task<int> BindSrmUserRole(List<SrmUserRoleSaveDto> list, int opOrgId)
        {
            try
            {
                if (list == null || list.Count == 0)
                {
                    return 0;
                }
                var newList = new List<SrmUserRoleMapEntity>();
                if (list?.Count > 0)
                {
                    foreach (var item in list)
                    {
                        var roleAllList = await _roleRepository.GetAllListAsync(it => it.SystemId == (int)DoraSysIdentifier.SRM && it.OrgId == opOrgId);
                        if (item.RoleIdList?.Count > 0)
                        {

                            var roleIdIdHash = item.RoleIdList.ToHashSet();
                            foreach (var roleId in roleIdIdHash)
                            {
                                if (roleAllList == null || roleAllList.Count == 0)
                                {
                                    newList.Add(new SrmUserRoleMapEntity() { UserId = item.UserId, RoleId = roleId });
                                }
                                else if(roleAllList.Exists(it=>it.Id==roleId))
                                {
                                    newList.Add(new SrmUserRoleMapEntity() { UserId = item.UserId, RoleId = roleId });
                                }
                            }
                        }

                        if (roleAllList?.Count > 0)
                        {
                            var roleAllIdList = roleAllList.Select(it => it.Id).ToList();
                            if (roleAllIdList?.Count > 0)
                            {
                                await _srmUserRoleMapRepository.DeleteByUserIdAndRoleIdList(item.UserId, roleAllIdList);
                            }
                        }
                    }
                }
                else
                {
                    return 0;
                }
                var userIdList = list.Select(p => p.UserId).Distinct().ToList();
                //await _srmUserRoleMapRepository.DeleteByUserIdList(userIdList);

                var num = 0;
                if (newList.Count > 0)
                {
                    num = await _srmUserRoleMapRepository.CreateRange(newList);
                }
                else
                {
                    num = 1;
                }

                #region 更新员工的缓存权限
                try
                {

                    if (userIdList?.Count > 0)
                    {
                        foreach (var eId in userIdList)
                        {
                            _ = RefreshRedisToken(eId);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"SaveRolePermission error:{ex.Message} {ex.StackTrace}");
                }
                #endregion
                return num;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        public async Task<ResultDto> ResetPassword(Guid userId, string password)
        {
            var entity = await GetById(userId);
            if (entity == null)
            {
                return ResultDto.Error("用户不存在", false);
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                return ResultDto.Error("密码不能为空", false);
            }

            var saltOldPassword = entity.Password;
            var saltNewPassword = DEncryptHelper.MD5Salt(password, entity.PasswordSalt);
            var mobilePassward = DEncryptHelper.GetInitPassword(entity.Mobile, entity.PasswordSalt);
            //if (saltNewPassword == mobilePassward)
            //{
            //    return ResultDto.Error("请不要使用默认密码作为新密码", false);
            //}
            if (saltNewPassword == saltOldPassword)
            {
                return ResultDto.Error("请使用和原密码不一样的新密码", false);
            }

            entity.Password = DEncryptHelper.MD5Salt(password, entity.PasswordSalt);

            var result = await _repository.UpdatePassword(entity);
            if (result)
            {
                return ResultDto.Success("重置成功", result);
            }
            else
            {
                return ResultDto.Error("重置失败", result);
            }
        }

        public async Task<bool> RefreshRedisToken(Guid userId)
        {
            try
            {

                var user = await GetById(userId);
                if (user == null)
                {
                    return false;
                }

                var permissions = new List<PermissionEntity>();
                if (user.IsSuperAdmin == 1)
                {
                    permissions = await _permissionRepository.GetAllListAsync();
                }
                else
                {
                    permissions = await _permissionRepository.GetSrmAuthedListByUserId(user.Id);
                }


                var authKeyList = new List<AuthKeyItem>();


                if (permissions?.Count > 0)
                {
                    //authKeyList = permissions.Select(p => p.AuthKey).ToList();

                    foreach (var item in permissions)
                    {
                        authKeyList.Add(new AuthKeyItem() { AuthKey = item.AuthKey, Name = item.Name, Icon = item.Icon, Sort = item.Sort });
                    }
                }
                var userDto = await TokenHelper.GetIdentityUserDtoAsync(userId.ToString());
                if (userDto == null)
                {
                    _ = TokenHelper.InvalidTokenAsync(userId.ToString());
                    return false;
                }
                userDto.Supplier.Id = user.SupplierId;
                userDto.AuthKeyList = authKeyList;
                return await TokenHelper.SetIdentityUserAsync(user.Id.ToString(), userDto);
            }
            catch (Exception ex)
            {
                _ = WriteOperationLog(OperationType.Error, new { userId, ex.Message, ex.StackTrace }, Guid.Empty, "系统", "SrmUserService RefreshRedisToken");
                Console.WriteLine($"SrmUserService RefreshRedisToken error:{ex.Message} {ex.StackTrace}");
                return false;
            }
        }

        public async Task<List<Guid>> GetIdListByRoleIdList(List<Guid> roleIdList)
        {
            var systemList = await _srmUserRoleMapRepository.GetListByRoleIdList(roleIdList);
            return systemList.Select(p => p.UserId).ToList();
        }

        public async Task<ResultDto> ResetPassword4Forget(string mobile, string code, string password)
        {
            var entity = await _repository.GetByVerifiedMobile(mobile);
            if (entity == null)
            {
                return new ResultDto(ResultCode.Fail, "用户不存在", null);
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                return new ResultDto(ResultCode.Fail, "密码不能为空", null);
            }
            if (GenerateVerifyCode.GetVerifyCode(mobile) != code)
            {
                return new ResultDto(ResultCode.Fail, "验证码错误", null);
            }

            var saltOldPassword = entity.Password;
            var saltNewPassword = DEncryptHelper.MD5Salt(password, entity.PasswordSalt);
            var mobilePassward = DEncryptHelper.GetInitPassword(entity.Mobile, entity.PasswordSalt);
            //if (saltNewPassword == mobilePass ward)
            //{
            //    return new ResultDto(ResultCode.Fail, "请不要使用默认密码作为新密码", null);
            //}
            if (saltNewPassword == saltOldPassword)
            {
                return new ResultDto(ResultCode.Fail, "请使用和原密码不一样的新密码", null);
            }

            entity.Password = saltNewPassword;

            var isSuccess = await _repository.UpdatePassword(entity);
            if (isSuccess)
            {
                GenerateVerifyCode.RemoveVerifyCode(mobile);
                return new ResultDto(ResultCode.Success, "修改成功，请重新登录", null);
            }
            return new ResultDto(ResultCode.Fail, "修改失败,请重试", null);
        }

        /// <summary>
        /// 用户禁用
        /// </summary>
        /// <param name="id"></param>
        /// <param name="opId"></param>
        /// <param name="opName"></param>
        /// <returns></returns>
        public async Task<bool> Disable(Guid id, Guid opId, string opName)
        {
            var entity = await _repository.FirstOrDefaultAsync(id);
            if (entity == null)
            {
                return false;
            }

            entity.IsDisabled = 1;
            entity.UpdatedTime = DateTime.Now;
            entity.UpdatedUserId = opId;
            entity.UpdatedUserName = opName;

            var result = await _repository.IsDisabled(entity);
            return result;
        }

        /// <summary>
        /// 用户启用
        /// </summary>
        /// <param name="id"></param>
        /// <param name="opId"></param>
        /// <param name="opName"></param>
        /// <returns></returns>
        public async Task<bool> Enable(Guid id, Guid opId, string opName)
        {
            var entity = await _repository.FirstOrDefaultAsync(id);
            if (entity == null)
            {
                return false;
            }

            entity.IsDisabled = 0;
            entity.UpdatedTime = DateTime.Now;
            entity.UpdatedUserId = opId;
            entity.UpdatedUserName = opName;

            var result = await _repository.IsDisabled(entity);
            return result;
        }

        /// <summary>
        /// 用户冻结
        /// </summary>
        /// <param name="id"></param>
        /// <param name="opId"></param>
        /// <param name="opName"></param>
        /// <returns></returns>
        public async Task<bool> Frozen(Guid id, Guid opId, string opName)
        {
            var entity = await _repository.FirstOrDefaultAsync(id);
            if (entity == null)
            {
                return false;
            }

            entity.IsFrozen = 1;
            entity.UpdatedTime = DateTime.Now;
            entity.UpdatedUserId = opId;
            entity.UpdatedUserName = opName;

            var result = await _repository.IsFrozen(entity);
            return result;
        }

        /// <summary>
        /// 用户解冻
        /// </summary>
        /// <param name="id"></param>
        /// <param name="opId"></param>
        /// <param name="opName"></param>
        /// <returns></returns>
        public async Task<bool> UnFrozen(Guid id, Guid opId, string opName)
        {
            var entity = await _repository.FirstOrDefaultAsync(id);
            if (entity == null)
            {
                return false;
            }

            entity.IsFrozen = 0;
            entity.UpdatedTime = DateTime.Now;
            entity.UpdatedUserId = opId;
            entity.UpdatedUserName = opName;

            var result = await _repository.IsFrozen(entity);
            return result;
        }

        /// <summary>
        /// 修改用户基本信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto> UpdateBaseInfo(SrmUserBaseInfoSaveDto input)
        {
            var entity = await _repository.FirstOrDefaultAsync(input.Id);
            if (entity == null)
            {
                return ResultDto.Error("用户不存在");
            }
            if (!string.IsNullOrEmpty(input.Phone) && !VerifyHelper.IsPhone(input.Phone.Trim()) && !VerifyHelper.IsMobilePhone(input.Phone.Trim()))
            {
                return ResultDto.Error("请输入正确的电话号码");
            }
            if (!string.IsNullOrEmpty(input.QQAccount) && !VerifyHelper.IsNotNagtive(input.QQAccount.Trim()))
            {
                return ResultDto.Error("请输入正确的QQ号码");
            }

            entity.Avatar = input.Avatar;
            entity.Sex = input.Sex;
            entity.Email = input.Email;
            entity.Phone = input.Phone;
            entity.QQAccount = input.QQAccount;
            entity.WxAccount = input.WxAccount;
            entity.PersonalNote = input.PersonalNote;

            var result = await _repository.UpdateBaseInfo(entity);
            if (result)
            {
                var userDto = await TokenHelper.GetIdentityUserDtoAsync(entity.Id.ToString());
                userDto.Avatar = input.Avatar;
                await TokenHelper.SetIdentityUserAsync(entity.Id.ToString(), userDto);
                return ResultDto.Success("修改成功");
            }
            else
            {
                return ResultDto.Error("修改失败");
            }
        }

        ///// <summary>
        ///// 生成工号,企业简称首字母+数字自增长
        ///// </summary>
        ///// <param name="orgId"></param>
        ///// <returns></returns>
        //private async Task<ResultDto<string>> GenerateJobNumber(int orgId)
        //{
        //    var orgInfo = await _organizationRepository.GetOrganizationInfoById(orgId);
        //    if (orgInfo == null)
        //    {
        //        return ResultDto<string>.Error("生成工号:组织机构不存在");
        //    }

        //    if (string.IsNullOrWhiteSpace(orgInfo.LevelPath))
        //    {
        //        return ResultDto<string>.Error("生成工号:组织机构层级路径为空");
        //    }

        //    var arrIds = orgInfo.LevelPath.Split(',', StringSplitOptions.RemoveEmptyEntries);
        //    var orgTopId = int.Parse(arrIds[0]);
        //    var orgTopInfo = await _organizationRepository.GetOrganizationInfoById(orgTopId);
        //    if (orgTopInfo == null)
        //    {
        //        return ResultDto<string>.Error("生成工号:顶级组织机构不存在");
        //    }

        //    if (string.IsNullOrWhiteSpace(orgTopInfo.ShortCode))
        //    {
        //        return ResultDto<string>.Error("生成工号:顶级组织机构简称首字母未设置");
        //    }
        //    var allOrgs = await _organizationRepository.GetSubOrganizations(orgTopId);
        //    var orgIdList = allOrgs.Select(it => it.Id).ToList();
        //    if (orgIdList == null || orgIdList.Count == 0)
        //    {
        //        return ResultDto<string>.Error("生成工号:组织机构及其下属不存在");
        //    }

        //    var orgCNAbbrSpell = orgTopInfo.ShortCode;
        //    var orgUserCount = await _tasOrgUserMapRepository.GetCountByOrgIdList(orgIdList);
        //    orgUserCount++;
        //    var jobNumber = $"{orgCNAbbrSpell}{orgUserCount.ToString().PadLeft(6, '0')}";
        //    return ResultDto<string>.Success(jobNumber);
        //}

        /// <summary>
        /// 修改用户手机号
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto> UpdateMobile(SrmUserEntity entity)
        {
            if (entity == null)
            {
                return ResultDto.Error("用户不存在");
            }

            var result = await _repository.UpdateMobile(entity);
            if (result)
            {
                return ResultDto.Success("修改成功");
            }
            else
            {
                return ResultDto.Error("修改失败");
            }
        }

        /// <summary>
        /// 修改用户的供应商Id
        /// </summary>
        /// <param name="srmUserId"></param>
        /// <param name="supplierId"></param>
        /// <returns></returns>
        public async Task<ResultDto> UpdateSupplierId(Guid srmUserId,int supplierId)
        {
            if (Guid.Empty.Equals(srmUserId) || supplierId<=0)
            {
                return ResultDto.Error("参数非法");
            }

            var result = await _repository.UpdateSupplierId(srmUserId, supplierId);
            if (result)
            {
                return ResultDto.Success("修改成功");
            }
            else
            {
                return ResultDto.Error("修改失败");
            }
        }
        
        /// <summary>
        /// 根据角色编号绑定用户角色
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roleNO"></param>
        /// <returns></returns>
        public async Task<int> BindRoleWithRoleNO(Guid userId, string roleNO)
        {
            try
            {
                var user = await GetById(userId);
                var role =await _roleRepository.GetByRoleNo(roleNO);
                if (user == null || role==null)
                {
                    return 0;
                }

                var newList = new List<SrmUserRoleMapEntity>();
                newList.Add(new SrmUserRoleMapEntity() { UserId = userId, RoleId = role.Id });

                await _srmUserRoleMapRepository.DeleteByUserIdAndRoleIdList(userId, new List<Guid>() { role.Id});

                var num = 0;
                if (newList.Count > 0)
                {
                    num = await _srmUserRoleMapRepository.CreateRange(newList);
                }
                else
                {
                    num = 1;
                }

                #region 更新员工的缓存权限
                try
                {
                    _ = RefreshRedisToken(userId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"BindRoleWithRoleNO error:{ex.Message} {ex.StackTrace}");
                }
                #endregion
                return num;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据角色编号解绑用户角色
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roleNO"></param>
        /// <returns></returns>
        public async Task<int> UnBindRoleWithRoleNO(Guid userId, string roleNO)
        {
            try
            {
                var role = await _roleRepository.GetByRoleNo(roleNO);
                if (role == null)
                {
                    return 0;
                }

                var newList = new List<SrmUserRoleMapEntity>();
                newList.Add(new SrmUserRoleMapEntity() { UserId = userId, RoleId = role.Id });

                var num = await _srmUserRoleMapRepository.DeleteByUserIdAndRoleIdList(userId, new List<Guid>() { role.Id });
                
                #region 更新员工的缓存权限
                try
                {
                    _ = RefreshRedisToken(userId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"UnBindRoleWithRoleNO error:{ex.Message} {ex.StackTrace}");
                }
                #endregion
                return num;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 更新环信Id
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto> UpdateHxUserName(Guid userId, string hxUserName)
        {
            var entity = new SrmUserEntity() { Id = userId, HxUserName = hxUserName };

            var result = await _repository.UpdateHxUserName(entity);
            if (result)
            {
                return ResultDto.Success("修改成功");
            }
            else
            {
                return ResultDto.Error("修改失败");
            }
        }

        /// <summary>
        /// 获取某个供应商下的所有用户
        /// </summary>
        /// <param name="supplierId">供应商Id</param>
        /// <param name="notInUserId">要排除的用户id</param>
        /// <returns></returns>
        public async Task<List<SrmUserListDto>> GetListBySupplierIdButOne(int supplierId,Guid notInUserId)
        {
            if (supplierId <= 0)
            {
                return new List<SrmUserListDto>();
            }
            var list = await _repository.GetListBySupplierIdButOne(supplierId, notInUserId);
            return list;
        }

        /// <summary>
        /// 获取某个供应商下的管理员用户
        /// </summary>
        /// <param name="supplierId"></param>
        /// <param name="roleNo"></param>
        /// <returns></returns>
        public async Task<List<SrmUserListDto>> GetSrmAdminUserListBySupplierId(int supplierId, string roleNo)
        {
            if (supplierId <= 0)
            {
                return new List<SrmUserListDto>();
            }
            var list = await _repository.GetSrmAdminUserListBySupplierId(supplierId, roleNo);
            return list;
          
        }
    }
}
